using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Wicresoft.OmsClient.OmsService;

namespace Wicresoft.OmsClient
{
    class StateChecker
    {
        private Thread thrCheck;

        public StateChecker()
        {
            thrCheck = new Thread(new ThreadStart(Main));
        }

        public void StartService()
        {
            if (thrCheck == null)
                thrCheck = new Thread(new ThreadStart(Main));
            thrCheck.Start();
        }

        public void StopService()
        {
            thrCheck.Abort();
        }

        private static void Main()
        {
            OMSService oms = new OMSService();
            UserService.GetUserInfoFromOMS();
            if (!string.IsNullOrEmpty(SyncConfigManage.UserName) && !string.IsNullOrEmpty(SyncConfigManage.Password))
                UserService.IsAuthorized = UserService.CheckUser(SyncConfigManage.UserName, SyncConfigManage.Password) == 1 ? true : false;
            else
                UserService.IsAuthorized = false;
            while (true)
            {
                int syncinterval = SyncConfigManage.SyncInterval * 1000;
                try
                {
                    string url = SyncConfigManage.ProviderUrl;
                    if (url == "")
                    {
                        StateLight.Gray();
                        Thread.Sleep(syncinterval);
                        continue;
                    }
                    oms.Url = url;
                    if (oms.CheckState() && UserService.IsAuthorized)
                        StateLight.Green();
                    else
                        StateLight.Red();
                    
                }
                catch (Exception ex)
                {
                    StateLight.Gray();
                    Logger.Exception("Check thread Main Exception", ex);
                }                

                Thread.Sleep(syncinterval);
            }
        }
    }
}
